package com.singzi.leetcode.N400;

public class T0400 {
    public static void main(String[] args) {
        Solution0400 solution0400 = new Solution0400();
        System.out.println(solution0400.findNthDigit(2890));
    }

}
class Solution0400 {

    public int findNthDigit(int n) {
        if(n < 10) return n;

        int result = 0;

        int index = getIndex(n);
        System.out.println(index);
        int sum = 9;
        for (int i = 1; i < index; i++) {
            sum += 9*Math.pow(10, i)*(i+1);
            System.out.println(sum);

        }

        System.out.println(n);
        int remain = n-sum;
        int r1 = remain/(index+1);
        System.out.println(r1);
        int r2 = remain%(index+1);
        int index_number;
        if(r2==0){
            index_number = (int) (r1 + Math.pow(10,index)-1);
            return index_number%10;
        }
        else{
            index_number = (int) (r1 + Math.pow(10,index));
            System.out.println(index_number);
            int index2 = index+1-r2;
            while (index2>0){
                index_number = index_number/10;
                result = index_number%10;
                index2--;
            }
            return result;
        }




    }
    public int getIndex(int n){

        int index = 1;
        int sum = 9;
        while(n-sum>0){
            sum += 9*Math.pow(10, index)*(index+1);
            index++;
        }
        return index-1;
    }
}